package com.example.rxjava.utils

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.createDataStore
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import java.io.IOException

class DataStoreManager {

    companion object {
        private const val PREFERENCE_NAME = "jack_data"

        private lateinit var dataStore: DataStore<Preferences>

        private val instance: DataStoreManager by lazy {
            DataStoreManager()
        }

        @JvmStatic
        fun get(): DataStoreManager {
            return instance
        }
    }

    fun init(context: Context) {
        dataStore = context.createDataStore(PREFERENCE_NAME)
    }

    suspend fun saveString(name: String, value: String) {
        val key = stringPreferencesKey(name)
        dataStore.edit {
            it[key] = value
        }
    }

    suspend fun getString(name: String): String {
        val key = stringPreferencesKey(name)
        val data = dataStore.data
            .catch {
                // 当读取数据遇到错误时，如果是 `IOException` 异常，发送一个 emptyPreferences 来重新使用
                // 但是如果是其他的异常，最好将它抛出去，不要隐藏问题
                if (it is IOException) {
                    it.printStackTrace()
                    emit(emptyPreferences())
                } else {
                    throw it
                }
            }
            .map {
                it[key] ?: ""
            }
        return data.first()
    }
}